package com.ridbor001.demo.service;

import com.ridbor001.demo.bean.RDBCourse;
import com.ridbor001.demo.bean.*;
import com.ridbor001.demo.dao.RDBCourseDAO;
import com.ridbor001.demo.dao.RDBEvaluationDAO;
import com.ridbor001.demo.dao.RDBGradeDAO;
import org.springframework.stereotype.Service;

import java.sql.SQLException;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class RDBEvaluationService {
    RDBEvaluationDAO rdbEvaluationDAO = new RDBEvaluationDAO();
    RDBCourseDAO rdbCourseDAO = new RDBCourseDAO();
    RDBGradeDAO rdbGradeDAO = new RDBGradeDAO();
    private static final Map<String, String> DIMENSION_ZH = Map.of(
            "teaching_method", "教学方法",
            "teaching_effect", "教学效果",
            "teaching_attitude", "教学态度"
    );
    public Map<String, String> getAllDimensionTranslations() {
        Map<String, String> map = DIMENSION_ZH;
        return map;
    }

    // 获取待评教课程（基于数据库查询）
    public List<RDBCourse> getPendingCourses(String studentId) throws SQLException {
        return rdbEvaluationDAO.getPendingEvaluations(studentId);
    }

//计算平均分
    public Map<String, Double> calculateAverageScores(List<RDBEvaluation> evals) {
        return evals.stream()
                .flatMap(e -> e.getItems().stream())
                .collect(Collectors.groupingBy(
                        RDBEvaluationItem::getDimension,
                        Collectors.averagingDouble(RDBEvaluationItem::getScore)
                ));
    }

    // 收集评论
    public List<String> collectComments(List<RDBEvaluation> evals) {
        return evals.stream()
                .flatMap(e -> e.getItems().stream())
                .map(RDBEvaluationItem::getComment)
                .filter(comment -> comment != null && !comment.isBlank())
                .collect(Collectors.toList());
    }

    // 获取教师所有课程的评教详情
    public Map<RDBCourse, List<RDBEvaluation>> getTeacherEvaluationsWithDetails(String teacherId) throws SQLException {
        // 1. 获取教师所有课程
        List<RDBCourse> teacherCourses = rdbCourseDAO.getCoursesByTeacher(teacherId);

        if (teacherCourses.isEmpty()) {
            return Collections.emptyMap();
        }

        // 2. 提取课程ID集合
        List<String> courseIds = teacherCourses.stream()
                .map(RDBCourse::getCourseId)
                .collect(Collectors.toList());

        // 3. 获取关联评教
        List<RDBEvaluation> relatedEvals = rdbEvaluationDAO.getEvaluationsByCourseIds(courseIds);

        // 4. 按课程分组
        Map<String, List<RDBEvaluation>> evalGroups = relatedEvals.stream()
                .collect(Collectors.groupingBy(RDBEvaluation::getCourseId));

        // 5. 创建课程ID到课程对象的映射
        Map<String, RDBCourse> courseMap = teacherCourses.stream()
                .collect(Collectors.toMap(RDBCourse::getCourseId, course -> course));

        // 6. 构建结果
        Map<RDBCourse, List<RDBEvaluation>> result = new HashMap<>();
        evalGroups.forEach((courseId, evals) -> {
            RDBCourse course = courseMap.get(courseId);
            if (course != null) {
                result.put(course, evals);
            }
        });

        return result;
    }

    public void addEvaluation(RDBEvaluation evaluation) throws SQLException {
        // 添加评教主表记录
        rdbEvaluationDAO.addEvaluationWithItems(evaluation);
    }
    public Map<RDBCourse, Map<String, Double>> getTeacherEvaluationStats(String teacherId) throws SQLException {
        Map<RDBCourse, List<RDBEvaluation>> courseEvals = getTeacherEvaluationsWithDetails(teacherId);

        if (courseEvals.isEmpty()) {
            return Collections.emptyMap();
        }

        return courseEvals.entrySet().stream()
                .collect(Collectors.toMap(
                        Map.Entry::getKey,
                        entry -> calculateAverageScores(entry.getValue())
                ));
    }


    public Map<RDBCourse, List<String>> getTeacherEvaluationComments(String teacherId) throws SQLException {
        Map<RDBCourse, List<RDBEvaluation>> courseEvals = getTeacherEvaluationsWithDetails(teacherId);

        if (courseEvals.isEmpty()) {
            return Collections.emptyMap();
        }

        return courseEvals.entrySet().stream()
                .collect(Collectors.toMap(
                        Map.Entry::getKey,
                        entry -> collectComments(entry.getValue())
                ));
    }


    // 新增维度翻译方法
    public String translateDimension(String dimension) {
        return DIMENSION_ZH.getOrDefault(dimension, dimension);
    }
    public Map<RDBCourse, List<RDBEvaluation>> getEvaluatedCoursesWithDetails(String studentId) throws SQLException {
        List<RDBCourse> evaluatedCourses =rdbEvaluationDAO.getEvaluatedCoursesByStudent(studentId);
        if (evaluatedCourses.isEmpty()) {
            return Collections.emptyMap();
        }

        List<String> courseIds = evaluatedCourses.stream()
                .map(RDBCourse::getCourseId)
                .collect(Collectors.toList());

        List<RDBEvaluation> evaluations = rdbEvaluationDAO.getEvaluationsByCourseIds(courseIds);

        Map<String, RDBCourse> courseMap = evaluatedCourses.stream()
                .collect(Collectors.toMap(RDBCourse::getCourseId, course -> course));

        Map<String, List<RDBEvaluation>> groupedEvals = evaluations.stream()
                .collect(Collectors.groupingBy(RDBEvaluation::getCourseId));

        Map<RDBCourse, List<RDBEvaluation>> result = new HashMap<>();
        groupedEvals.forEach((courseId, evalList) -> {
            RDBCourse course = courseMap.get(courseId);
            if (course != null) {
                result.put(course, evalList);
            }
        });

        return result;
    }

}